import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:wechat_decode/components/decode_input_field.dart';
import 'package:wechat_decode/components/unify_button.dart';
import 'package:wechat_decode/constants/global.dart';

import '../states/decode_progress_state.dart';

/// 微信文件解码页
class WxDecodePage extends StatefulHookConsumerWidget {
  const WxDecodePage({super.key, required this.title});

  final String title;

  @override
  ConsumerState<WxDecodePage> createState() => _WxDecodePageState();

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty('title', title));
  }
}

class _WxDecodePageState extends ConsumerState<WxDecodePage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  late TextEditingController _inputController;
  late TextEditingController _outputController;
  late final bool _isCopy;

  @override
  void initState() {
    _inputController = TextEditingController(text: Global.prefs.getString('input'));
    _outputController = TextEditingController(text: Global.prefs.getString('output'));
    _isCopy = Global.prefs.getBool('isCopy') ?? false;
    super.initState();
  }

  @override
  void dispose() {
    _inputController.dispose();
    _outputController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var isCopy = useState(_isCopy);
    var decodeProgress = ref.watch(decodeProgressNotifierProvider);
    var isComputed = decodeProgress.isComputed;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Form(
          key: _formKey,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  children: [
                    const Text('是否复制不需要解码的文件:'),
                    Checkbox(
                      visualDensity: VisualDensity.compact,
                      splashRadius: 0,
                      value: isCopy.value,
                      onChanged: (value) {
                        isCopy.value = value!;
                      },
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                // 输入框
                DecodeInputField(
                  label: '微信数据存储地址',
                  controller: _inputController,
                  pathRequiredExist: true,
                  enabled: isComputed,
                ),
                const SizedBox(height: 8),
                DecodeInputField(
                  label: '转储地址',
                  controller: _outputController,
                  enabled: isComputed,
                  validator: (value) {
                    if (_inputController.text == _outputController.text) {
                      return '转储地址不能与微信数据存储地址相同';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 20),
                // 解码按钮
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    UnifyButton(
                      enabled: isComputed,
                      onPressed: () async {
                        if ((_formKey.currentState as FormState).validate()) {
                          // 验证通过提交数据
                          var input = _inputController.text;
                          var output = _outputController.text;
                          Global.prefs.setBool('isCopy', isCopy.value);
                          // 缓存上次输入的地址
                          await Global.prefs.setString('input', input);
                          await Global.prefs.setString('output', output);
                          ref
                              .read(decodeProgressNotifierProvider.notifier)
                              .task(input: input, output: output, isCopy: isCopy.value);
                        }
                      },
                      text: isComputed ? '解码' : '正在解码中...',
                    ),
                    const SizedBox(width: 20),
                    if (!isComputed)
                      UnifyButton(
                        onPressed: () async {
                          ref.read(decodeProgressNotifierProvider.notifier).cancelTask();
                        },
                        text: '取消',
                      ),
                  ],
                ),
                const SizedBox(height: 20),
                // 进度条
                Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    LinearProgressIndicator(
                      value: decodeProgress.total == 0 ? 0 : decodeProgress.current / decodeProgress.total,
                    ),
                    Text('[${decodeProgress.current} / ${decodeProgress.total}]当前执行：${decodeProgress.printout}'),
                  ],
                )
              ],
            ),
          )),
    );
  }
}
